<!DOCTYPE html>
<script src="../../resources/gc.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>
function soon() { return new Promise(resolve => setTimeout(resolve, 0)); }
async function becomesTrue(predicate) {
  while (!predicate()) await soon();
}

function createSelfConnectedNode(context) {
  const gain = context.createGain();
  gain.connect(gain);
}

promise_test(async () => {
  await asyncGC();
  await becomesTrue(() => internals.audioHandlerCount() == 0);

  let context = new OfflineAudioContext(2, 1024, 44100);
  let initialCount = internals.audioHandlerCount();
  createSelfConnectedNode(context);
  assert_greater_than(internals.audioHandlerCount(), 0);

  // Need to render to clean up a cycle on an offline context.
  await context.startRendering();

  // Wait until the gain node's handler has been destroyed to declare victory.
  await asyncGC();
  await becomesTrue(() => internals.audioHandlerCount() <= initialCount);
}, "No crash should occur when a node connected to itself is collected.");
</script>
